<template>

  <div class="app-container" v-if="showForm">
      <div class="query-wrapper" style="margin-bottom: 20px;" model="queryParams">
        <el-input v-model="queryParams.fcCode" style="width: 160px" placeholder="F/C Code" clearable/> &nbsp;&nbsp; &nbsp;&nbsp;
       
      <el-select
        v-model="queryParams.vesselName"
        filterable
        clearable
        placeholder="Vessel"
        style="width:180px"
        @change="selectVessel"
      >
        <el-option :key="item.vesselName" :label="item.vesselName" :value="item.vesselName" v-for="item in vessels">
        </el-option>
      </el-select> 
      &nbsp;&nbsp;
      <el-select v-model="queryParams.voyageNo" filterable clearable placeholder="Voyage" @change="selectVoyage"  style="width:120px">
        <el-option :key="item.voyageNo" :label="item.voyageNo" :value="item.voyageNo" v-for="item in voyages">
        </el-option>
      </el-select> 
      &nbsp;&nbsp;
      <!-- <el-select v-model="queryParams.pol" filterable clearable placeholder="POL">
          <el-option :key="item.portName" :label="item.portName" :value="item.portName" v-for="item in pols">
          </el-option>
    </el-select>
       &nbsp;&nbsp;
      <el-select v-model="queryParams.pod" filterable clearable placeholder="POD">
        <el-option :key="item.portName" :label="item.portName" :value="item.portName" v-for="item in pods">
        </el-option>
      </el-select>&nbsp;&nbsp; -->
     
      <el-select v-model="queryParams.clientName" filterable clearable allow-create placeholder="Charterer" style="width:250px">
        <el-option :key="item.fullName" :label="item.fullName" :value="item.fullName" v-for="item in clients">
        </el-option>
      </el-select>    &nbsp;&nbsp; 
        <el-button type="primary"  icon="search"  @click="search">{{ $t("ship.button.search") }}</el-button>
        <SearchReset :query-params="queryParams" @reset="resetQuery"></SearchReset>    
        <span>&nbsp;&nbsp;&nbsp;&nbsp;</span>
        <el-button type="primary" plain icon="plus" @click="addClickEvent"  v-hasPermi="['invoice:edit']">
          {{ $t("ship.button.plus") }}
        </el-button>
      </div>
 
   <el-table stripe :border="true"  :data="listData" style="width: 100%" @sort-change="handleSortChange">  
     <el-table-column prop="invoiceDate" label="Date" width="150" sortable="custom" :sort-orders="['descending', 'ascending']" /> 
     <el-table-column prop="receiver" label="Mesers" width="150" sortable="custom" :sort-orders="['descending', 'ascending']" />
     <el-table-column prop="vesselName" label="Loaded on board" width="150" sortable="custom" :sort-orders="['descending', 'ascending']" />
     <el-table-column prop="voyageNo" label="Voyage No." width="150" sortable="custom" :sort-orders="['descending', 'ascending']" />
     <el-table-column prop="sailedOn" label="Sale on" width="150" sortable="custom" :sort-orders="['descending', 'ascending']" />
     <el-table-column prop="pol" label="Port of Loading" width="150" sortable="custom" :sort-orders="['descending', 'ascending']" />
     <el-table-column prop="pod" label="Port of Delivery"  sortable="custom" :sort-orders="['descending', 'ascending']" /> 
     <el-table-column label="Operation" width="160"   v-hasPermi="['invoice:edit']">
       <template #default="scope">
         <span class="btn-primary" @click="editClickEvent(scope.row)">{{ $t("ship.button.edit") }}</span
         >&nbsp;&nbsp;
         <span class="btn-primary" @click="removeClickEvent(scope.row.id)">{{ $t("ship.button.remove") }}</span>
         &nbsp;&nbsp;
         <span class="btn-primary" @click="handleExport(scope.row)">{{ $t("ship.button.export") }}</span>
         &nbsp;&nbsp;
       </template>
     </el-table-column>
   </el-table>
 
   <pagination
     v-show="total > 0"
     :total="total"
     :page="queryParams.pageNum"
     :limit="queryParams.pageSize"
     @pagination="pageQuery"
     style="float: right"
   />
  </div>
  
   <!--添加记录-->
   <div class="add-container" v-else style="padding:40px 40px">
    <el-form :model="formParam" :rules="rules" ref="custForm">
       <el-row>
         <el-col :span="8">
           <el-form-item label="FC Code" label-width="160px" prop="fcCode" required>
            <el-select v-model="formParam.fcCode" @change="selectFcCode" style="width:300px">
               <el-option v-for="item in fcList"
               :key = "item.fcCode"
               :value = "item.fcCode"
               :label="item.fcCode"
                />
             </el-select> 
           </el-form-item>
         </el-col>
         <el-col :span="8">
           <el-form-item label="Date" label-width="160px" prop="invoiceDate" required>
            <el-date-picker value-format="YYYY-MM-DD" v-model="formParam.invoiceDate" class="ipt"
            placeholder="Please choose Date" />
           </el-form-item>
         </el-col>
       </el-row>
	   
       <el-row>
	      <el-col :span="8">
           <el-form-item label="Mesers" label-width="160px" prop="receiver" required>
            <el-input v-model="formParam.receiver" class="ipt" placeholder="Mesers" />
           </el-form-item>
         </el-col>
         <el-col :span="8">
           <el-form-item  label="Voyage No."  label-width="160px" prop="voyageNo" required>
            <el-input v-model="formParam.voyageNo" class="ipt" placeholder="Voyage No" />
           </el-form-item>
         </el-col>
       </el-row>
	   
       <el-row>
         <el-col :span="8">
           <el-form-item  label="Loaded On Board" label-width="160px" prop="vesselName" required>
            <el-input v-model="formParam.vesselName" class="ipt" placeholder="Loaded On Board" />
           </el-form-item>
         </el-col>        
         <el-col :span="8">
           <el-form-item  label="Sailed On" label-width="160px" prop="sailedOn" required>
            <el-date-picker value-format="YYYY-MM-DD" v-model="formParam.sailedOn" placeholder="Sailed On" />
           </el-form-item>
         </el-col>    
       </el-row> 
       <el-row> 
       <el-col :span="8">
           <el-form-item  label="Port Of Loading" label-width="160px" prop="pol" required>
            <el-input v-model="formParam.pol" class="ipt" placeholder="Port Of Loading" />
           </el-form-item>
         </el-col>
         <el-col :span="8">
           <el-form-item label="Port Of Delivery"  label-width="160px" prop="pod" required>
            <el-input v-model="formParam.pod" class="ipt" placeholder="Port Of Delivery" />
           </el-form-item>
         </el-col>
       </el-row>    
	   
       <el-table :data="formParam.details" :rules="detailRules" class="problem-table" stripe  row-key="id">   
          <el-table-column label="B/L No." align="center" prop="blNo" width="240">
            <template #default="scope">
              <el-select v-model="scope.row.blNo" clearable allow-create filterable style="width:180px">
                <el-option v-for="item in blNos"  :key = "item" :value = "item" :label="item" />
              </el-select> 
            </template> 
          </el-table-column>
          <el-table-column  label="Quantity"  prop="quantity" align="center"/> 
          <el-table-column  label="Revenue ton"   align="center">
            <template #header>
              <el-dropdown trigger="click"  @command="handleCommand">
               <span class="el-dropdown-link">
                  Revenue Ton
                 <el-icon class="el-icon--right">
                   <arrow-down />
                 </el-icon>
               </span>
               <template #dropdown>
                 <el-dropdown-menu>
                   <el-dropdown-item command="0">CBM</el-dropdown-item>
                   <el-dropdown-item command="1">MT</el-dropdown-item>
                 </el-dropdown-menu>
               </template>
             </el-dropdown>
             </template>
                 <template #default="scope"> 
                    {{formParam.feeType==0 ?scope.row.volume+" CBM": (scope.row.weight*1000) +" KG"}}
                   <!-- <el-form-item v-if="formParam.feeType==0"  :prop="'details.'+scope.$index+'.volume'"   style="margin: auto;"> 
                       <el-input-number :precision="2" v-model="scope.row.volume"  class="ipt"  style="text-align: center;"/>   
                   </el-form-item> 
                   <el-form-item v-else :prop="'details.'+scope.$index+'.weight'"  style="margin: auto;">
                     <el-input-number   v-model="scope.row.weight"  class="ipt"  style="text-align: center;"/> 
                   </el-form-item>  -->
                 </template> 
          </el-table-column>
          <el-table-column  label="Rate" prop="freightRate" align="center"/>
          <el-table-column  label="Freight" prop="freight" align="center"/>
          <el-table-column  label="Total Amount" align="right" prop="totalAmount1"/>
        </el-table>   
		
		<div style="padding:20px 0 0 0;border-bottom:1px solid #000">  
        <table width="100%">
          <tbody>
        <tr>
        <td width="14.2%" align="left" >
            <div style="padding:20px 30px;font-size:16px"> 
          <span style="font-size:18px">Total:</span>
          </div>
        </td>
        <td width="14.2%" align="center" >
            <div style="padding:20px 30px;font-size:16px"> 
          {{quantityTotal}}
          </div>
        </td>
        
        <td width="14.2%" align="center" >
            <div style="padding:20px 30px;font-size:16px"> 
          {{formParam.feeType== 0? sumCBM.toFixed(2) +" CBM" : sumWeight.toFixed(2)+" KG"}}  
          </div>
        </td>
        <td width="14.2%" align="center" >
            <div style="padding:20px 30px;font-size:16px">  
          </div>
        </td>
        <td width="14.2%" align="center" >
            <div style="padding:20px 30px;font-size:16px">  
          </div>
        </td>
        <td width="14.2%" align="right" >
            <div style="padding:20px 10px;font-size:16px"> 
          &nbsp; {{amountEndTotal.toFixed(2)}} &nbsp;{{formParam.details[0]?formParam.details[0].currency:""}} 
          </div>
        </td>
        </tr>
      </tbody> 
      </table> 
		</div>
		<div style="padding:20px 0 0 0;border-bottom:1px solid #000"> 
		  <el-row>
             <el-col :span="8">
			  </el-col>
			  <el-col :span="8">
				<div style="padding:20px 30px;font-size:16px"> 
				   <span style="font-size:18px"> Ex.Rate </span>
				   <span v-if="formParam.details[0]">
				       <el-input-number  v-model="formParam.exRate" style="width:220px" class="ipt" placeholder="Ex.Rate "></el-input-number>
				   </span>
				</div>
			  </el-col>	
			   <el-col :span="4">
				  <div style="padding:20px 30px;font-size:16px;float:right"> 
				   <span style="font-size:18px">AMOUNT: </span>&nbsp; {{formParam.details[0]?formParam.details[0].currency:""}} 				 
				  </div>
			  </el-col>	
			  <el-col :span="4">
				  <div style="padding:20px 30px;font-size:16px;float:right"> 
				   &nbsp; &nbsp; {{amountEndTotal.toFixed(2)}}
				  </div>
			</el-col>			  
		  </el-row>
		</div>		
		<el-row>
		  <el-col :span="24">
			<div class="dialog-footer"> 
			  <el-button type="primary" :loading="isLoading" @click="backListHandle">Back</el-button>
			  <el-button type="primary" :loading="isLoading" @click="submitForm">Submit</el-button> 
			</div>
		   </el-col>
        </el-row>
     </el-form> 
  </div> 
 </template>
 
<script lang="ts" setup name="invoice">
import { ref, onMounted, reactive } from "vue";
import { ElNotification ,ElMessageBox } from "element-plus"; 
import { downloadFile } from "@/utils/downloadFile";
import { convertDate } from "@/utils/date"
import service from "@/utils/request"; 
const route = useRoute(); 
const custForm = ref(null);
const dialogTitle = ref("");
const initForm = {
   id: null,
   invoiceDate: null,
   fcCode: null,   
   freightDate: convertDate(new Date()),
   salesId: null,
   clientName: null,
   mobile: null,
   receiver: null,
   contact: null,
   vesselName: null,
   voyageNo: null,
   sailedOn: null,
   pol: null,
   pod: null,
   bookingNo: null,   
   blNo: null,
   units: null, 
   details: [
   ],
   beneficiaryName: null,
   beneficiaryAddress: null,
   accountNo: null,
   bankName:null,
   bankAddress: null,
   exRate:null,
   country: null,
   province:null,
   swiftCode:null,
   amount:null,
   feeType:0
 };
 const formParam = reactive(Object.assign({}, initForm));
 const isLoading = ref(false);
const total = ref(0);
const  amountTotal = ref(0);
const  amountEndTotal = ref(0);
const  quantityTotal = ref(0); 
let sumRevenueTon =  0
const sumCBM = ref(0);
const sumWeight = ref(0);
const rules = ref({ 
fcCode : [{ required: true, message: "FC Code is required" }],
receiver: [{ required: true, message: "Mesers is required" }],
invoiceDate: [{ required: true, message: "Date is required" }],
vesselName : [{ required: true, message: "Loaded On Board is required" }],
voyageNo : [{ required: true, message: "Voyage No. is required" }],
blNo: [{ required: true, message: "B/L No. is required" }],
sailedOn : [{ required: true, message: "Sailed On is required" }],
pol: [{ required: true, message: "Port Of Loading is required" }],
pod: [{ required: true, message: "Port Of Delivery is required" }],
});

 const detailRules = ref([])
 
 const showForm = ref(true)
 showForm.value = !route.query?.showForm 

 
 const queryParams = reactive({
   pageNum: 1,
   pageSize: 20,
   fixtureCode: null,
   blType: null,
   orderByColumn: undefined,
   isAsc: undefined,
   carrierCode:null,
   vesselName:null,
   voyageNo:null,
   pol:null,
   pod:null,
   clientName:null,
 });
// 搜索下拉框数据
const carriers = ref([] ); 
const vessels = ref([] );
const voyages = ref([]);
const pols = ref([])
const pods = ref([])
const clients = ref([])
const selectVessel =()=>{ 
  queryParams.voyageNo = null
  queryParams.pol = null
  queryParams.pod = null
  voyages.value = []
  pols.value = []
  pods.value = []
  if(queryParams.vesselName != null && queryParams.vesselName != undefined){ 
    let item = vessels.value.find(n=>n.vesselName == queryParams.vesselName) 
    if(item){
      voyages.value = item.schedules
    } 
  } 
}
const selectVoyage = async()=>{
   //@ts-ignore
  let item = voyages.value.find(n=>n.voyageNo == queryParams.voyageNo)
  if(item){
    pods.value = item.pods
    pols.value = item.pols
  }
}

let blNos = reactive([])
let fcList = reactive([])
const listData = ref([]); 
 const refreshTable = async () => {
   let result = await service.get("/shipping/invoice/getTable", { params: queryParams });
   if(result){
      listData.value = result.data;
      total.value = result.total;
   }
 };
const resetQuery = (data) => {
  Object.assign(queryParams, data)
  listData.value = []
  total.value = 0
} 
const recordData=ref()
  watch(() => showForm,
    () => {
      if (showForm) {
          recordData.value = JSON.parse(localStorage.getItem('RECORD_DATA')) 
          if(recordData.value != null){
              Object.keys(recordData.value).forEach(key => {
              formParam[key] = recordData.value[key]       
            })
          } 
      }
    },
  {immediate: true }
)
 
const dialogFormVisible = ref(false); 
 const editClickEvent = (row: any) => { 
   localStorage.setItem('RECORD_DATA', JSON.stringify(row))
 
   dialogTitle.value = "Update Invoice";
   dialogFormVisible.value = true;
   isAdd = false;
   Object.keys(initForm).forEach((k) => (formParam[k] = row[k]));
   showForm.value=false
   //router.push({ path: '/contract/invoice',query:{showForm: true} }) 
 };
 
 let isAdd = false;
 const addClickEvent = () => {
    localStorage.setItem('RECORD_DATA', JSON.stringify({}))
   Object.assign(formParam, initForm);
   showForm.value=false
   //router.push({ path: '/contract/invoice',query:{showForm: true} }) 
 }; 
 
 const submitForm = () => {
   custForm.value.validate(async valid => {
      if (!valid) { 
        return;
      }
      if (isLoading.value) return;
      isLoading.value = true;
      isAdd = formParam.id == null
      formParam.amount = amountEndTotal.value.toFixed(2)
      formParam.currency = formParam.details[0].currency
      formParam.quantity = quantityTotal.value 
      await service[isAdd ? "post" : "put"]("shipping/invoice", formParam);
      ElNotification.success({ title: "Prompt information", message: "save successful!", position: "bottom-right" });
      //dialogFormVisible.value = false;
      isLoading.value = true;
      //refreshTable();
      backListHandle()
   });
 };
 
 const pageQuery = async e => {
   queryParams.pageNum = e.page;
   queryParams.pageSize = e.limit;
   refreshTable();
 };
 
 const search = () => {
   refreshTable();
 };

  
 const handleSortChange = async (column: any) => {
   queryParams.orderByColumn = column.prop;
   queryParams.isAsc = column.order; //动态取值排序顺序
   refreshTable();
 };
 
 const removeClickEvent = id => {
   ElMessageBox.confirm("Confirm to Remove the data？", "Confirmation Information", {
     type: "warning",
     confirmButtonText: "Confirm",
     cancelButtonText: "Cancel"
   }).then(async () => {
     await service.delete(`shipping/invoice/${id}`);
     refreshTable();
     ElNotification.success({ title: "Prompt information", message: "Delete successfully!", position: "bottom-right" });
   });
 };
 
 const backListHandle=()=>{
  //router.push({ path: '/contract/invoice' }) 
  showForm.value= true
} 

const selectFcCode = async()=>{
	let item = fcList.find(item => item.fcCode == formParam.fcCode)   
  if(item){
    formParam.clientName = item.clientName
	  formParam.vesselName = item.vesselName
	  formParam.voyageNo = item.voyageNo
	  formParam.pol = item.pol
	  formParam.pod = item.pod 
    formParam.sailedOn = item.sailedOn
    formParam.details = item.details
    formParam.feeType = item.feeType
    amountEndTotal.value=0
    amountTotal.value=0
    quantityTotal.value=0
    sumWeight.value=0
    sumCBM.value=0
    sumRevenueTon=0
    if(formParam.details != null){
      for(let i in formParam.details){
        formParam.details[i].quantity=1
        formParam.details[i].freightRate = formParam.details[i].unitPrice
        if(formParam.feeType == 0){
          formParam.details[i].revenueTon = formParam.details[i].volume + '  CBM'  
          sumRevenueTon += Number(formParam.details[i].volume) 
        }else{         
          formParam.details[i].revenueTon = formParam.details[i].weight + '  KG'  
          sumRevenueTon += Number(formParam.details[i].weight) 
        }
        //formParam.details[i].weight = formParam.details[i].weight*1000

        sumWeight.value +=  Number(formParam.details[i].weight*1000)
        sumCBM.value += Number(formParam.details[i].volume)
       
		    amountEndTotal.value+=Number(formParam.details[i].amount); 
        formParam.details[i].totalAmount1 = formParam.details[i].amount + ' ' + formParam.details[i].currency
        formParam.details[i].freight ="FRT"
        formParam.details[i].amount = formParam.details[i].unit 
		    amountTotal.value+=Number(formParam.details[i].unit);
		    quantityTotal.value+=Number(formParam.details[i].quantity); 
       
      }
    }
    if(formParam.feeType == 0){
        sumRevenueTon += " CBM"
    }else{
      sumRevenueTon += " KG"
    }
  }	
}

 function handleExport(row: any) {
   downloadFile("/shipping/invoice/export", row, `${new Date().getTime()}invoice.xlsx`);
}
 onMounted(async () => {
  service.get("/shipping/cargoManifest/import").then(result=>{blNos = result.data})   
  service.get("/shipping/freightConfirm/list").then(result=>{ fcList = result.data })  
  service.get("/shipping/schedule/getAllSchedule").then(result=>{  vessels.value = result.data})  
  service.get("/shipping/carrier/list").then(result=>{
    carriers.value = result.data;
  });
  
 service.get("/shipping/client/list").then(result=>{
  clients.value = result.data
 })
   
  // refreshTable();
  setTimeout(function(){selectFcCode()},100)
 });
 const handleCommand=( value)=>{
  formParam.feeType=value
 }


</script> 

<style scoped lang="scss">
  ::v-deep(.el-input__wrapper){
  width: 180px !important;
}
::v-deep(.el-input-number){
  margin: auto;
}
.el-dropdown-link {
  display: flex;
  align-items: center;
  font-size: 12px;
  line-height: 2;
}
.add-container {
padding-top: 30px;
background-color: #fafafa;
height: 100%;
}

.dialog-footer {
margin: 60px auto 0;
width: 100%;
text-align: center;
}
.d-center {
  display: flex;
  align-items: center;
  justify-content: center;
}
</style>